﻿namespace AVW.Server.RESTful.Base.backgroundServices
{
    public class ClearNginxLogsBackgroundService : BackgroundService
    {
        private readonly string m_nginx_log_path;
        /// <summary>
        /// 每天几点执行该定时任务
        /// </summary>
        private readonly int m_hours = 3;

        /// <summary>
        /// 清理多久的文件
        /// </summary>
        private readonly int m_clear_days = 30;

        private static int m_count;
        public ClearNginxLogsBackgroundService(IServiceProvider serviceProvider)
        {
            // todo
            m_nginx_log_path = @"/var/log/nginx";
        }

        private void DoWork(DateTime currentTime)
        {
            var paths = Directory.GetFiles(m_nginx_log_path);

            // 清垃圾
            foreach (var path in paths)
            {
                FileInfo file = new FileInfo(path);
                // 删除超过30天的垃圾文件
                if ((currentTime - file.LastWriteTime).Days > m_clear_days)
                {
                    File.Delete(path);
                }
            }

            // 备份error_log
            var error_log = Path.Combine(m_nginx_log_path, "error.log");
            if (File.Exists(error_log))
            {
                string format = currentTime.AddDays(-1).ToString("yyyy-MM-dd");
                File.Copy(error_log, Path.Combine(m_nginx_log_path, $"error_{format}.log"),true);
                File.WriteAllText(error_log, "");
            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {

                DateTime current = DateTime.Now;
                DateTime tomorrow = current.AddDays(1);
                // 下一次执行定时任务的时间
                DateTime nextExecuteTime = new DateTime(tomorrow.Year, tomorrow.Month, tomorrow.Day, m_hours, 0, 0);


                // 首次运行程序不执行
                if (m_count != 0)
                {
                    DoWork(current);
                }
                m_count++;
                var ms = (nextExecuteTime - current).TotalMilliseconds;
                await Task.Delay((int)ms, stoppingToken);
            }
        }
    }
}
